var tgd = tgd || {};
tgd.Contests = tgd.Contests || {};
tgd.Contests.SameGame = tgd.Contests.SameGame || {};
tgd.Contests.SameGame.Solver = tgd.Contests.SameGame.Solver || {};
tgd.Contests.SameGame.View = tgd.Contests.SameGame.View || {};

/*
 * Singleton
 * Data structure:  { Best : [ { Max : Number, Game : String, Date : Date }, ... ], Max : [Number, ...] }
 * The IDs passed to all methods are the puzzle IDs, which are one more then their location in the array.
 * e.g. ID == 1 is at array index == 0.
 */
tgd.Contests.SameGame.DAO = function () {
	var instance = (function() {
		var _data = JSON.parse(window.localStorage.getItem("SameGame"));

		function _clear() {
			_data = { Best : [], Max : [] };
			window.localStorage.setItem("SameGame", JSON.stringify(_data));
		}
		
		if (_data === null) {
			_clear();
		}
	
		return {  //public interface
			getBest : function(id) {
				_data.Best[id - 1].Max = parseInt(_data.Best[id - 1].Max);
				return _data.Best[id - 1];
			},
			getMax : function(id) {
				return parseInt(_data.Max[id - 1]);
			},
			setBest : function(id, val) {
				val.Max = parseInt(val.Max);
				if (_data.Best[id - 1] === undefined || val.Max > _data.Best[id - 1].Max) {
					_data.Best[id - 1] = val;
					window.localStorage.setItem("SameGame", JSON.stringify(_data));
				}
			},
			setMax : function(id, val) {
				val = parseInt(val);
				if (_data.Max[id - 1] === undefined || val > _data.Max[id - 1]) {
					_data.Max[id - 1] = val;
					window.localStorage.setItem("SameGame", JSON.stringify(_data));
				}
			},
			clear : function() {
				_clear();
			}
		};
	})();

	tgd.Contests.SameGame.DAO = function() {
		return instance;
	};

	return tgd.Contests.SameGame.DAO();
}
